<?php

/**
 * Initialisateur du Framework
 *
 * @category   McCube
 * @package    Root
 * @author     Leiha Sellier <leiha.sellier@gmail.com>
 * @license    http://creativecommons.org/licenses/by/3.0/  CC BY 3.0
 * @link       http://code.google.com/p/mechanics-cubes/
 */
class McCube_Bootstrap{

    protected static $_instance = null;

    /** */
    public static function getInstance($appPublic=''){
        if(!self::$_instance)
            $class = get_called_class();
            self::$_instance = new $class($appPublic);

        return self::$_instance;
    }

    /** */
    public static function registerPath(){
        set_include_path( get_include_path()
            .PATH_SEPARATOR.implode(PATH_SEPARATOR, func_get_args())
        );
    }

    /** */
    public static function autoloader($className){
        $classPath = str_replace('_' , DIRECTORY_SEPARATOR, $className);
        include_once $classPath.'.php';
    }

    // --------------------------------------------------

    public $fwRoot      = '';
    public $appRoot     = '';
    public $appLibrary  = '';
    public $environment = '';
    public $context     = '';
    protected $_classOfApplication = 'McCube_Bundle_Application';

    /** */
    public function __construct($appRoot){
        $this->fwRoot      = realpath(__DIR__   .DIRECTORY_SEPARATOR.'..').DIRECTORY_SEPARATOR;
        $this->appRoot     = realpath($appRoot).DIRECTORY_SEPARATOR;
        $this->appLibrary  = $this->appRoot.'library'.DIRECTORY_SEPARATOR;
        $this->environment = getenv('APPLICATION_ENV');

        $this->_initautoLoader();
        if($this->environment == 'production')
            include($this->fwRoot.'McCube'.DIRECTORY_SEPARATOR.'Debug'.DIRECTORY_SEPARATOR.'Fake.php');
        else
            include($this->fwRoot.'McCube'.DIRECTORY_SEPARATOR.'Debug.php');

        $this->_initNotifier();
        $this->_initErrorHandler();
    }

    /** */
    protected function _initNotifier(){
        McCube_Notifier::setContext($this->context);
    }

    /** */
    protected function _initErrorHandler(){
        set_error_handler    ('McCube_Error::handler');
        set_exception_handler('McCube_Exception::handler');
    }

    /** */
    protected function _initautoLoader(){
        self::registerPath(
             $this->fwRoot
            ,$this->appLibrary
        );
        spl_autoload_register('McCube_Bootstrap::autoloader');
    }

    /** */
    public function getApp(){
        $file = $this->appRoot.'Application.php';
        if(is_file($file)){
            if(!class_exists('Application')){
                throw new McCube_Exception_ClassNotFound('Application', $file);
            }
            return new Application($this->appRoot, $this->urlRoot, $this->environment);
        }
        return new $this->_classOfApplication($this->appRoot, $this->urlRoot, $this->environment);
    }
}